//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
/*++
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
Copyright (c) 1995-1999  Microsoft Corporation

Module Name:

msg.cpp

Abstract:


Notes:


--*/
/*
------------------------------------------------------------------------------
    Revision History
    Date                Author            Activity ID             Activity Headline
    2006-02-09          Wangxiaogang      CEDB00006280           Move RIL from public to bsp270
    2007-01-08          qinxuetao         CEDB00040729           Porting ril driver for CC/SMS
    2007-02-08          qinxuetao         CEDB200043651          Update ril driver for network and data service
    2007-07-12          qinxuetao         WM600009465            [shenzhen_FT]CU SIM fail to send short message
------------------------------------------------------------------------------
*/

#include "precomp.h"


//
// Broadcast message languages
//
static const BYTE g_rgbBroadcastLangs[] =
{
    15,         // RIL_DCSLANG_UNKNOWN
    0,          // RIL_DCSLANG_GERMAN
    1,          // RIL_DCSLANG_ENGLISH
    2,          // RIL_DCSLANG_ITALIAN
    3,          // RIL_DCSLANG_FRENSH
    4,          // RIL_DCSLANG_SPANISH
    5,          // RIL_DCSLANG_DUTCH
    6,          // RIL_DCSLANG_SWEDISH
    7,          // RIL_DCSLANG_DANISH
    8,          // RIL_DCSLANG_PORTUGUESE
    9,          // RIL_DCSLANG_FINNISH
    10,         // RIL_DCSLANG_NORWEGIAN
    11,         // RIL_DCSLANG_GREEK
    12,         // RIL_DCSLANG_TURKISH
    13,         // RIL_DCSLANG_HUNGARIAN
    14,         // RIL_DCSLANG_POLISH
    32,         // RIL_DCSLANG_CZECH
    33,         // RIL_DCSLANG_HEBREW
    34,         // RIL_DCSLANG_ARABIC
    35,         // RIL_DCSLANG_RUSSIAN
    36,         // RIL_DCSLANG_ICELANDIC
};
#define NUM_LANGUAGES   (sizeof(g_rgbBroadcastLangs) / sizeof(BYTE))


//
// Message storage locations
//
static const LPCSTR g_rgszMsgLocations[] =
{
    "",             // RIL_MSGLOC_UNKNOWN
    "BM",           // RIL_MSGLOC_BROADCAST
    "SM",           // RIL_MSGLOC_SIM
    "SR"            // RIL_MSGLOC_STATUSREPORT
};
#define NUM_MSGLOCS     (sizeof(g_rgszMsgLocations) / sizeof(LPCSTR))


//
// Message status values
//
static const DWORD g_rgdwMsgStats[] =
{
    RIL_MSGSTATUS_RECUNREAD,    // 0
    RIL_MSGSTATUS_RECREAD,      // 1
    RIL_MSGSTATUS_STOUNSENT,    // 2
    RIL_MSGSTATUS_STOSENT,      // 3
};
#define NUM_MSGSTATS    (sizeof(g_rgdwMsgStats) / sizeof(DWORD))


//
// Appends specified GSM broadcast DCS value value to the generated DCS range
//
static void AppendLangString(const LPCSTR szAppend, LPSTR& szWalk, const UINT cbOut, UINT& rcbUsed)
{
    FUNCTION_TRACE(AppendLangString);
    UINT cbAppend = strlen(szAppend);

    if ((1 < rcbUsed) && (rcbUsed + 1 <= cbOut))  // Need for and room for ','
    {
        *szWalk = ',';  // Overwrite '\0'
        szWalk++;
        *szWalk = '\0';  // Add '\0' back
        rcbUsed++;  // Caller has already counted the '\0', so just count the ',' here
    }

    if (rcbUsed + cbAppend <= cbOut)
    {
        strncpyz(szWalk, szAppend, cbOut - rcbUsed);
        szWalk += cbAppend;
        rcbUsed += cbAppend;
    }
    else
    {
        DEBUGCHK(FALSE);
    }
}


//
// Generates a GSM broadcast DCSs range string corresponding to the specified language mask
//
static void MakeBroadcastLangRange(const DWORD dwLanguages, const LPSTR szOut, const UINT cbOut)
{
    FUNCTION_TRACE(MakeBroadcastLangRange);
    UINT i;
    LPSTR szWalk = szOut;
    UINT cbUsed = 0;
    char szNumber[3];

    *szWalk = '\0';

    // The empty string is sufficient for RIL_DCSLANG_ALL.

    if (RIL_DCSLANG_ALL != dwLanguages)
    {
        cbUsed = 1;  // Account for the '\0'

        // Iterate through all bits of the mask to see which languages to add
        for (i = 0; (i < sizeof(DWORD)*8) && (i < NUM_LANGUAGES); i++)
        {
            if ((dwLanguages >> i) & 0x01)
            {
                _itoa(g_rgbBroadcastLangs[i], szNumber, 10);
                DEBUGCHK('\0' == szNumber[1] || '\0' == szNumber[2]);
                AppendLangString(szNumber, szWalk, cbOut, cbUsed);
            }
        }
    }
}


static void MakeBroadcastMsgIDs(const RILRANGE rgrrRange[], DWORD dwNumRanges, const LPSTR szOut, const UINT cbOut)
{
    LPSTR szWalk = szOut;
    LPSTR szEnd = szOut + cbOut;
    DWORD cbRange = 0;
    char szRange[64];
    char c_szRangeFmt[] = ",%u-%u";
    char c_szSingleFmt[] = ",%u";
    char * szRangeFmt = c_szRangeFmt + 1;
    char * szSingleFmt = c_szSingleFmt + 1;

    for (DWORD dwCurrentRange = 0; dwCurrentRange < dwNumRanges; dwCurrentRange++)
    {
        if (rgrrRange[dwCurrentRange].dwMinValue == rgrrRange[dwCurrentRange].dwMaxValue)
        {
            cbRange = _snprintfz(szRange, 64, szSingleFmt, rgrrRange[dwCurrentRange].dwMinValue);
        }
        else
        {
            cbRange = _snprintfz(szRange, 64, szRangeFmt, rgrrRange[dwCurrentRange].dwMinValue, rgrrRange[dwCurrentRange].dwMaxValue);
        }

        if (szWalk + cbRange < szEnd)
        {
            strcpy(szWalk, szRange);
            szWalk += cbRange;
        }
        else
        {
            break;
        }

        szRangeFmt = c_szRangeFmt;
        szSingleFmt = c_szSingleFmt;
    }

    *szWalk = '\0';
}

//
// Set a flag in the language mask correponding to the
//    specified GSM broadcast DCS value
//
static BOOL AppendLanguage(const UINT nValue, DWORD& rdwLanguages)
{
    FUNCTION_TRACE(AppendLanguage);
    UINT i;
    BOOL fRet = FALSE;

    for (i = 0 ; i < NUM_LANGUAGES; i++)
    {
        if (nValue == g_rgbBroadcastLangs[i])
        {
            DEBUGCHK(i < 32);
            rdwLanguages |= (0x01 << i);
            break;
        }
    }
    return fRet;
}


//
// Parses a range of GSM broadcast DCSs into a language mask
//
static BOOL ParseBroadcastLangRange(LPCSTR szRange, DWORD& rdwLanguages)
{
    FUNCTION_TRACE(ParseBroadcastLangRange);
    UINT nValue1;
    UINT nValue2;
    UINT i;
    BOOL fRet = FALSE;

    if (*szRange)
    {
        // Start off with none...
        rdwLanguages = 0;

        while (1)
        {
            if (!ParseUInt(szRange, TRUE, nValue1, szRange))
            {
                goto Error;
            }
            if (MatchStringBeginning(szRange, "-", szRange) &&
                ParseUInt(szRange, TRUE, nValue2, szRange))
            {
                // This is a mini-range
                DEBUGCHK(nValue1 < nValue2);
                for (i = nValue1; i <= nValue2; i++)
                {
                    (void)AppendLanguage(i, rdwLanguages);
                }
            }
            else
            {
                (void)AppendLanguage(nValue1, rdwLanguages);
            }

            // If there is no trailing comma, we're done
            if (!MatchStringBeginning(szRange, ",", szRange))
            {
                break;
            }
        }
    }
    else
    {
        // An empty string implies all languages.
        rdwLanguages = RIL_DCSLANG_ALL;
    }
    fRet = TRUE;

    Error:
    return fRet;
}

BOOL ParseGetLocation(const LPCSTR szRspOrig, UINT& rnLocation, LPCSTR& rszPointer)
{
    FUNCTION_TRACE(ParseGetLocation);
    char szLocation[MAX_PATH];
    UINT nLocation;

    LPCSTR szRsp = szRspOrig;

    // Parse "<xxx_location>"
    if (!ParseString(szRsp, szLocation, MAX_PATH, szRsp))
    {
        return FALSE;
    }

    for (nLocation = NUM_MSGLOCS-1; nLocation > 0; nLocation--)
    {
        if (!strcmp(szLocation, g_rgszMsgLocations[nLocation]))
        {
            break;
        }
    }

    rnLocation = nLocation;
    rszPointer = szRsp;
    return TRUE;
}

static BOOL ParseGetLocationAmount(LPCSTR szRsp, LPCSTR& rszPointer, PUINT pLocation, PUINT pUsed, PUINT pTotal)
{
    FUNCTION_TRACE(ParseGetLocationAmount);
    UINT nLocation;
    UINT nUsed;
    UINT nTotal;

    // Go past initial ',' if it's there
    if (*szRsp==',')
    {
        szRsp++;
    }

    // Parse "<xxx_location>"
    if (!ParseGetLocation(szRsp, nLocation, szRsp))
    {
        return FALSE;
    }

    // Parse ",<xxx_used>"
    if (!MatchStringBeginning(szRsp, ",", szRsp) ||
        !ParseUInt(szRsp, TRUE, nUsed, szRsp))
    {
        return FALSE;
    }

    // Parse ",<xxx_total>"
    if (!MatchStringBeginning(szRsp, ",", szRsp) ||
        !ParseUInt(szRsp, TRUE, nTotal, szRsp))
    {
        return FALSE;
    }

    *pLocation = nLocation;
    *pUsed = nUsed;
    *pTotal = nTotal;
    rszPointer = szRsp;
    return TRUE;
}

//
//
//
static HRESULT ParseGetMsgServiceOptionsRsp(LPCSTR szRsp, void*& pBlob, UINT& cbBlob)
{
    FUNCTION_TRACE(ParseGetMsgServiceOptionsRsp);
    HRESULT hr = E_FAIL;
    RILMSGSERVICEINFO* prmsi = NULL;
    UINT nValue;
    UINT nLocation;
    UINT nUsed;
    UINT nTotal;

    pBlob = NULL;
    cbBlob = 0;

    prmsi = (RILMSGSERVICEINFO*)AllocBlob(sizeof(RILMSGSERVICEINFO));
    if (!prmsi)
    {
        hr = E_OUTOFMEMORY;
        goto Error;
    }
    memset(prmsi, 0x00, sizeof(RILMSGSERVICEINFO));
    prmsi->cbSize = sizeof(RILMSGSERVICEINFO);

    // Parse "<prefix>+CSMS: <svc_type>"
    if (!ParseRspPrefix(szRsp, szRsp)                  ||
        !MatchStringBeginning(szRsp, "+CSMS: ", szRsp) ||
        !ParseUInt(szRsp, TRUE, nValue, szRsp))
    {
        goto Error;
    }

    if (!nValue)
    {
        prmsi->dwService = RIL_MSGSVCTYPE_PHASE2;
    }
    else if (1 == nValue)
    {
        prmsi->dwService = RIL_MSGSVCTYPE_PHASE2PLUS;
    }
    else
    {
        prmsi->dwService = RIL_MSGSVCTYPE_UNKNOWN;
    }
    prmsi->dwParams |= RIL_PARAM_MSI_SERVICE;

    // Parse ",<incoming>"
    prmsi->dwMsgClasses = RIL_MSGCLASS_NONE;
    if (!MatchStringBeginning(szRsp, ",", szRsp) ||
        !ParseUIntAndVerifyAbove(szRsp, TRUE, 2, nValue, szRsp))
    {
        goto Error;
    }

    if (1 == nValue)
    {
        prmsi->dwMsgClasses |= RIL_MSGCLASS_INCOMING;
    }

    // Parse ",<outgoing>"
    if (!MatchStringBeginning(szRsp, ",", szRsp) ||
        !ParseUIntAndVerifyAbove(szRsp, TRUE, 2, nValue, szRsp))
    {
        goto Error;
    }

    if (1 == nValue)
    {
        prmsi->dwMsgClasses |= RIL_MSGCLASS_OUTGOING;
    }

    // Parse ",<broadcast><postfix>"
    if (!MatchStringBeginning(szRsp, ",", szRsp) ||
        !ParseUIntAndVerifyAbove(szRsp, TRUE, 2, nValue, szRsp)   ||
        !ParseRspPostfix(szRsp, szRsp))
    {
        goto Error;
    }

    if (1 == nValue)
    {
        prmsi->dwMsgClasses |= RIL_MSGCLASS_BROADCAST;
    }
    prmsi->dwParams |= RIL_PARAM_MSI_MSGCLASSES;

    // Parse "<prefix>+CPMS: "
    if (!ParseRspPrefix(szRsp, szRsp)                  ||
        !MatchStringBeginning(szRsp, "+CPMS: ", szRsp))
    {
        goto Error;
    }

    // Parse Read fields
    if (!ParseGetLocationAmount(szRsp, szRsp, &nLocation, &nUsed, &nTotal))
    {
        goto Error;
    }

    prmsi->dwReadLocation = nLocation;
    prmsi->dwReadUsed = nUsed;
    prmsi->dwReadTotal = nTotal;
    prmsi->dwParams |= RIL_PARAM_MSI_READLOCATION | RIL_PARAM_MSI_READUSED | RIL_PARAM_MSI_READTOTAL;

    // Note: If write or store fields are missing, we use the values from the last set of fields.
    // Therefore, we don't check the return value from the following two ParseGetLocationAmount calls.
    // This works around Wavecom issues with both versions of Wavecom modules where they don't report
    // all three sets of fields.

    // Parse Write fields
    ParseGetLocationAmount(szRsp, szRsp, &nLocation, &nUsed, &nTotal);
    prmsi->dwWriteLocation = nLocation;
    prmsi->dwWriteUsed = nUsed;
    prmsi->dwWriteTotal = nTotal;
    prmsi->dwParams |= RIL_PARAM_MSI_WRITELOCATION | RIL_PARAM_MSI_WRITEUSED | RIL_PARAM_MSI_WRITETOTAL;

    // Parse Store fields
    ParseGetLocationAmount(szRsp, szRsp, &nLocation, &nUsed, &nTotal);
    prmsi->dwStoreLocation = nLocation;
    prmsi->dwStoreUsed = nUsed;
    prmsi->dwStoreTotal = nTotal;
    prmsi->dwParams |= RIL_PARAM_MSI_STORELOCATION | RIL_PARAM_MSI_STOREUSED | RIL_PARAM_MSI_STORETOTAL;

    ParseRspPostfix(szRsp, szRsp);
    pBlob = (void*)prmsi;
    cbBlob = sizeof(RILMSGSERVICEINFO);

    hr = S_OK;

    Error:
    if (FAILED(hr))
    {
        FreeBlob(prmsi);
    }
    return hr;
}

//
//
//
HRESULT RILDrv_GetMsgServiceOptions(DWORD dwParam)
{
    FUNCTION_TRACE(RILDrv_GetMsgServiceOptions);
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle)
    {
        hr = E_FAIL;
        goto Error;
    }

    if (!QueueCmd(pHandle, "AT+CSMS?;+CPMS?\r", CMDOPT_NONE, APIID_GETMSGSERVICEOPTIONS,
                  ParseGetMsgServiceOptionsRsp, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }

    Error:
    return hr;
}


//
//
//
HRESULT RILDrv_SetMsgServiceOptions(DWORD dwParam, const RILMSGSERVICEINFO* lpMsgServiceInfo)
{
    FUNCTION_TRACE(RILDrv_SetMsgServiceOptions);
    CNotificationData* pnd = NULL;
    char szCmd[MAX_PATH];
    LPSTR szWalk = szCmd;
    UINT nValue;
    BOOL fStorageSpecified = TRUE;
    RILMSGSTORAGEINFO rmsi; memset(&rmsi,0,sizeof(rmsi)); // zero struct
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle || !lpMsgServiceInfo)
    {
        hr = E_FAIL;
        goto Error;
    }

    // Add "AT"
    (void)strncpyz(szWalk, "AT", MAX_PATH - (szWalk - szCmd));
    szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
    DEBUGCHK(NULL != szWalk);

    if (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_SERVICE)
    {
        if (RIL_MSGSVCTYPE_PHASE2 == lpMsgServiceInfo->dwService)
        {
            nValue = 0;
        }
        else if (RIL_MSGSVCTYPE_PHASE2PLUS == lpMsgServiceInfo->dwService)
        {
            nValue = 1;
        }
        else
        {
            DEBUGCHK(FALSE);
        }

        // Add "+CSMS=<service>"
        (void)_snprintfz(szWalk, MAX_PATH - (szWalk - szCmd), "+CSMS=%u", nValue);
        szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
        DEBUGCHK(NULL != szWalk);
    }


#ifdef WAVECOM_DRIVER
    // HW-SPECIFIC: WaveCom hardware reports data for only one storage location

    // Figure out the storage value we need to set
    if (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_READLOCATION)
    {
        nValue = lpMsgServiceInfo->dwReadLocation;
    }
    else if (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_WRITELOCATION)
    {
        nValue = lpMsgServiceInfo->dwWriteLocation;
    }
    else if (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_STORELOCATION)
    {
        nValue = lpMsgServiceInfo->dwStoreLocation;
    }
    else
    {
        fStorageSpecified = FALSE;
    }

    // Set the storage, if it is provided
    if (fStorageSpecified)
    {
        DEBUGCHK(NUM_MSGLOCS > nValue);

        if (RIL_MSGLOC_UNKNOWN == nValue)
        {
            hr = E_INVALIDARG;
            goto Error;
        }

        // Add ";", if needed
        if (szWalk != szCmd + 2)
        {  // NO_TYPO: 30
            (void)strncpyz(szWalk, ";", MAX_PATH - (szWalk - szCmd));
            szWalk++;
        }

        // Add "+CPMS=<storage>"
        (void)_snprintfz(szWalk, MAX_PATH - (szWalk - szCmd), "+CPMS=\"%s\"", g_rgszMsgLocations[nValue]);
        szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
        DEBUGCHK(NULL != szWalk);

        rmsi.dwReadLocation = nValue;
        rmsi.dwWriteLocation = nValue;
        rmsi.dwStoreLocation = nValue;
        rmsi.dwParams = RIL_PARAM_MSTI_ALL;
    }
#else  // WAVECOM_DRIVER


    if ((lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_READLOCATION) ||
        (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_WRITELOCATION) ||
        (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_STORELOCATION))
    {
        // At least one location is specified

        // Add ";", if needed
        if (szWalk != szCmd + 2)
        {  // NO_TYPO: 30
            (void)strncpyz(szWalk, ";", MAX_PATH - (szWalk - szCmd));
            szWalk++;
        }

        // Add "+CPMS="
        (void)strncpyz(szWalk, "+CPMS=", MAX_PATH - (szWalk - szCmd));
        szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
        DEBUGCHK(NULL != szWalk);

        if (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_READLOCATION)
        {
            nValue = lpMsgServiceInfo->dwReadLocation;
            if (RIL_MSGLOC_UNKNOWN == nValue)
            {
                hr = E_INVALIDARG;
                goto Error;
            }
            DEBUGCHK(NUM_MSGLOCS > nValue);

            // Add "<read_storage>"
            (void)_snprintfz(szWalk, MAX_PATH - (szWalk - szCmd), "\"%s\"", g_rgszMsgLocations[nValue]);
            szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
            DEBUGCHK(NULL != szWalk);

            rmsi.dwReadLocation = nValue;
            rmsi.dwParams |= RIL_PARAM_MSTI_READLOCATION;
        }

        // Add ","
        (void)strncpyz(szWalk, ",", MAX_PATH - (szWalk - szCmd));
        szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
        DEBUGCHK(NULL != szWalk);

        if (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_WRITELOCATION)
        {
            nValue = lpMsgServiceInfo->dwWriteLocation;
            if (RIL_MSGLOC_UNKNOWN == nValue)
            {
                hr = E_INVALIDARG;
                goto Error;
            }
            DEBUGCHK(NUM_MSGLOCS > nValue);

            // Add "<write_storage>"
            (void)_snprintfz(szWalk, MAX_PATH - (szWalk - szCmd), "\"%s\"", g_rgszMsgLocations[nValue]);
            szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
            DEBUGCHK(NULL != szWalk);

            rmsi.dwWriteLocation = nValue;
            rmsi.dwParams |= RIL_PARAM_MSTI_WRITELOCATION;
        }

        // Add ","
        (void)strncpyz(szWalk, ",", MAX_PATH - (szWalk - szCmd));
        szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
        DEBUGCHK(NULL != szWalk);

        if (lpMsgServiceInfo->dwParams & RIL_PARAM_MSI_STORELOCATION)
        {
            nValue = lpMsgServiceInfo->dwStoreLocation;
            if (RIL_MSGLOC_UNKNOWN == nValue)
            {
                hr = E_INVALIDARG;
                goto Error;
            }
            DEBUGCHK(NUM_MSGLOCS > nValue);

            // Add "<store_storage>"
            (void)_snprintfz(szWalk, MAX_PATH - (szWalk - szCmd), "\"%s\"", g_rgszMsgLocations[nValue]);
            szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
            DEBUGCHK(NULL != szWalk);

            rmsi.dwStoreLocation = nValue;
            rmsi.dwParams |= RIL_PARAM_MSTI_STORELOCATION;
        }
    }
#endif // WAVECOM_DRIVER


    // Add "<CR>"
    (void)strncpyz(szWalk, "\r", MAX_PATH - (szWalk - szCmd));  // NO_TYPO: 30

    if (rmsi.dwParams)
    {
        pnd = new CNotificationData;
        if (pnd)
        {
            rmsi.cbSize = sizeof(RILMSGSTORAGEINFO);
            if (!pnd->InitFromRealBlob(RIL_NOTIFY_MSGSTORAGECHANGED, &rmsi, sizeof(RILMSGSTORAGEINFO)))
            {
                delete pnd;
                pnd = NULL;
            }
        }
    }
    if (!QueueCmd(pHandle, szCmd, CMDOPT_NONE, APIID_SETMSGSERVICEOPTIONS, NULL, pnd, hr))
    {
        hr = E_FAIL;
        goto Error;
    }
    pnd = NULL;

    Error:
    return hr;
}


//
//
//
static HRESULT ParseGetMsgConfigRsp(LPCSTR szRsp, void*& pBlob, UINT& cbBlob)
{
    FUNCTION_TRACE(ParseGetMsgConfigRsp);
    UINT nValue;
    char szAddress[MAX_PATH];
    //    char szLanguageRange[MAX_PATH];
    RILMSGCONFIG* prmc = NULL;
    HRESULT hr = S_OK;
    ENCODING_TYPE etEncoding = ENCODING_GSMDEFAULT_HEX;

    pBlob = NULL;
    cbBlob = 0;

    prmc = (RILMSGCONFIG*)AllocBlob(sizeof(RILMSGCONFIG));
    if (!prmc)
    {
        hr = E_OUTOFMEMORY;
        goto Error;
    }
    memset(prmc, 0x00, sizeof(RILMSGCONFIG));
    prmc->cbSize = sizeof(RILMSGCONFIG);

    // Parse "<prefix>+CSCA: <svcctr_addr>,<type_of_addr><postfix>"
    if (!ParseRspPrefix(szRsp, szRsp)                               ||
        !MatchStringBeginning(szRsp, "+CSCA: ", szRsp)              ||
        !ParseString(szRsp, szAddress, MAX_PATH, szRsp)             ||
        !MatchStringBeginning(szRsp, ",", szRsp)                    ||
        !ParseUIntAndVerifyAbove(szRsp, TRUE, 0x100, nValue, szRsp) ||
        !ParseRspPostfix(szRsp, szRsp))
    {
        hr = E_FAIL;
        goto Error;
    }


#ifdef OEM2_DRIVER  // OEM2 uses GSM unpacked characters.
    etEncoding = ENCODING_GSMDEFAULT_UNICODE;
#elif defined(EMP_DRIVER)
    etEncoding = ENCODING_TECHARSET;
#endif

    // Convert data to address structure
    if (!StringToRILAddress(szAddress, (BYTE)nValue, prmc->raSvcCtrAddress, etEncoding))
    {
        hr = E_FAIL;
        goto Error;
    }
    prmc->dwParams |= RIL_PARAM_MC_SVCCTRADDRESS;

    pBlob = (void*)prmc;
    cbBlob = sizeof(RILMSGCONFIG);

    Error:
    if (FAILED(hr))
    {
        FreeBlob(prmc);
    }
    return hr;

}


//
//
//
HRESULT RILDrv_GetMsgConfig(DWORD dwParam)
{
    FUNCTION_TRACE(RILDrv_GetMsgConfig);
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle)
    {
        hr = E_FAIL;
        goto Error;
    }

    if (!QueueCmd(pHandle, "AT+CSCA?\r", CMDOPT_NONE, APIID_GETMSGCONFIG, ParseGetMsgConfigRsp, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }

    Error:
    return hr;
}


//
//
//
HRESULT RILDrv_SetMsgConfig(DWORD dwParam, const RILMSGCONFIG* lpMsgConfigInfo)
{
    FUNCTION_TRACE(RILDrv_SetMsgConfig);
    char szCmd[MAXLENGTH_MSGIDS + MAX_PATH * 3];
    LPSTR szWalk = szCmd;
    char szSvcCtrAddress[MAX_PATH];
    BYTE bTypeOfAddress;
    HRESULT hr = S_OK;
    ENCODING_TYPE etEncoding = ENCODING_GSMDEFAULT_HEX;
    
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle || !lpMsgConfigInfo)
    {
        hr = E_FAIL;
        goto Error;
    }

    (void)strncpyz(szWalk, "AT", MAX_PATH - (szWalk - szCmd));
    szWalk += 2;

    if (lpMsgConfigInfo->dwParams & RIL_PARAM_MC_SVCCTRADDRESS)
    {

#ifdef OEM2_DRIVER  // OEM2 uses GSM unpacked characters.
        etEncoding = ENCODING_GSMDEFAULT_UNICODE;
#elif defined(EMP_DRIVER)
        etEncoding = ENCODING_TECHARSET;
#endif
        
        hr = RILAddressToString(lpMsgConfigInfo->raSvcCtrAddress, szSvcCtrAddress, MAX_PATH, bTypeOfAddress, etEncoding);
        if (FAILED(hr))
        {
            goto Error;
        }
        (void)_snprintfz(szWalk, MAX_PATH - (szWalk - szCmd), "+CSCA=\"%s\",%u", szSvcCtrAddress, bTypeOfAddress);
        szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
        DEBUGCHK(NULL != szWalk);
    }

#ifdef WAVECOM_DRIVER
    (void)strncpyz(szWalk, "\r", MAX_PATH - (szWalk - szCmd));  // NO_TYPO: 30

    if (!QueueMultipartCmd(pHandle, szCmd, "AT+CSAS\r", CMDOPT_INTERMEDIATERESPONSE, APIID_SETMSGCONFIG, NULL, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }
#else
    (void)strncpyz(szWalk, ";+CSAS\r", MAX_PATH - (szWalk - szCmd));  // NO_TYPO: 30

    if (!QueueCmd(pHandle, szCmd, CMDOPT_NONE, APIID_SETMSGCONFIG, NULL, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }
#endif

    Error:
    return hr;
}

static RILCBMSGCONFIG * AllocCbMsgConfig(DWORD dwNumRanges)
{
    DWORD dwSize = sizeof(RILCBMSGCONFIG) + dwNumRanges * sizeof(RILRANGE);

    RILCBMSGCONFIG* prmc = (RILCBMSGCONFIG*)AllocBlob(dwSize);
    if (NULL != prmc)
    {
        memset(prmc, 0x00, dwSize);
        prmc->cbSize = dwSize;
    }

    return prmc;
}

//
//
//
static HRESULT ParseBroadcastMsgIDs(const LPCSTR szBroadcastMsgIDs,
                                    RILCBMSGCONFIG ** pprCbMsgConfig)
{
    DEBUGCHK(NULL != szBroadcastMsgIDs);

    HRESULT hr = S_OK;
    DWORD dwNumRanges;
    LPCSTR szDummy;
    DWORD dwNumIDs = 0;

    if (*szBroadcastMsgIDs)
    {
        dwNumIDs++;

        for (LPCSTR szPtr = szBroadcastMsgIDs; '\0' != *szPtr; szPtr++)
        {
            if (',' == *szPtr)
                dwNumIDs++;
        }
    }

    *pprCbMsgConfig = AllocCbMsgConfig(dwNumIDs);
    if (NULL == *pprCbMsgConfig)
    {
        hr = E_OUTOFMEMORY;
        goto Error;
    }

    if (!ParseRangesFromString(szBroadcastMsgIDs,
                               (*pprCbMsgConfig)->rgrrBroadcastMsgIDs,
                               dwNumRanges,
                               dwNumIDs,
                               szDummy))
    {
        hr = E_FAIL;
        goto Error;
    }

    DEBUGCHK(dwNumRanges == dwNumIDs);

Error:
    return hr;
}

//
//
//
static HRESULT ParseGetCellBroadcastMsgConfigRsp(LPCSTR szRsp, void*& pBlob, UINT& cbBlob)
{
    FUNCTION_TRACE(ParseGetCellBroadcastMsgConfigRsp);
    UINT nValue;
    BOOL fAccept = FALSE;
    char szLanguageRange[MAX_PATH];
    char szBroadcastMsgIDs[MAXLENGTH_MSGIDS];
    RILCBMSGCONFIG* prmc = NULL;
    HRESULT hr = S_OK;

    pBlob = NULL;
    cbBlob = 0;

    // Parse "<prefix>+CSCB: <mode>"
    if (!ParseRspPrefix(szRsp, szRsp)                  ||
        !MatchStringBeginning(szRsp, "+CSCB: ", szRsp) ||
        !ParseUIntAndVerifyAbove(szRsp, TRUE, 2, nValue, szRsp)) {
        hr = E_FAIL;
        goto Error;
    }

    // Cache accept value for when we have a structure allocated
    fAccept = (nValue == 0);

    // Parse ",<msg_ids>,<msg_langs><postfix>"
    if (!MatchStringBeginning(szRsp, ",", szRsp)                              ||
        !ParseString(szRsp, szBroadcastMsgIDs, MAXLENGTH_MSGIDS, szRsp))
    {
        hr = E_FAIL;
        goto Error;
    }

    // Parse broadcast message IDs
    // This also allocates the blob
    hr = ParseBroadcastMsgIDs(szBroadcastMsgIDs, &prmc);
    if (FAILED(hr))
    {
        goto Error;
    }

    prmc->fAccept = fAccept;
    prmc->dwParams |= (RIL_PARAM_CBMC_BROADCASTMSGIDS | RIL_PARAM_CBMC_ACCEPTIDS);

    if (MatchStringBeginning(szRsp, ",", szRsp))
    {
        if (!ParseString(szRsp, szLanguageRange, MAX_PATH, szRsp))
        {
            hr = E_FAIL;
            goto Error;
        }

        // Parse accepted languages
        if (!ParseBroadcastLangRange(szLanguageRange, prmc->dwBroadcastMsgLangs)) {
            hr = E_FAIL;
            goto Error;
        }

        prmc->dwParams |= RIL_PARAM_CBMC_BROADCASTMSGLANGS;
    }

    if (!ParseRspPostfix(szRsp, szRsp))
    {
        hr = E_FAIL;
        goto Error;
    }

    pBlob = (void*)prmc;
    cbBlob = prmc->cbSize;

    Error:
    if (FAILED(hr))
    {
        FreeBlob(prmc);
    }
    return hr;

}

//
//
//
HRESULT RILDrv_GetCellBroadcastMsgConfig(DWORD dwParam)
{
    FUNCTION_TRACE(RILDrv_GetCellBroadcastMsgConfig);
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle)
    {
        hr = E_FAIL;
        goto Error;
    }

    if (!QueueCmd(pHandle, "AT+CSCB?\r", CMDOPT_NONE, APIID_GETCBMSGCONFIG,
                  ParseGetCellBroadcastMsgConfigRsp, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }

    Error:
    return hr;
}

//
//
//
HRESULT RILDrv_SetCellBroadcastMsgConfig(DWORD dwParam, const RILCBMSGCONFIG* lpMsgConfigInfo)
{
    FUNCTION_TRACE(RILDrv_SetCellBroadcastMsgConfig);
    char szCmd[MAXLENGTH_MSGIDS + MAX_PATH * 3];
    LPSTR szWalk = szCmd;
#ifndef EMP_DRIVER
    char szCBMsgLangs[MAX_PATH];
#endif
    char szBroadcastMsgIDs[MAX_PATH];
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle || !lpMsgConfigInfo)
    {
        hr = E_FAIL;
        goto Error;
    }

    if (!(lpMsgConfigInfo->dwParams & RIL_PARAM_CBMC_ACCEPTIDS))
    {
        hr = E_INVALIDARG;
        goto Error;
    }

#ifdef EMP_DRIVER
    // EMP doesn't support 1 for <mode>
    // Note that <mode>=1 corresponds to fAccept=0
    if (0 == lpMsgConfigInfo->fAccept)
    {
        hr = E_NOTIMPL;
        goto Error;
    }
#endif

    (void)_snprintfz(szCmd, MAX_PATH, "AT+CSCB=%d", (lpMsgConfigInfo->fAccept?0:1));
    szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
    DEBUGCHK(NULL != szWalk);

#if defined (WAVECOM_DRIVER)
    // HW-SPECIFIC: WaveCom hardware does not allow parameters with reject mode
    if (lpMsgConfigInfo->fAccept)
#endif
    {
        if ((lpMsgConfigInfo->dwParams & RIL_PARAM_CBMC_BROADCASTMSGIDS))
        {
            MakeBroadcastMsgIDs(lpMsgConfigInfo->rgrrBroadcastMsgIDs,
                                (lpMsgConfigInfo->cbSize - sizeof(RILCBMSGCONFIG)) / sizeof(RILRANGE),
                                szBroadcastMsgIDs,
                                MAX_PATH);

            (void)_snprintfz(szWalk, MAX_PATH, ",\"%s\"", szBroadcastMsgIDs);
            szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
            DEBUGCHK(NULL != szWalk);

        }

#ifndef EMP_DRIVER
        // EMP doesn't support parameter <dcss>
        if (lpMsgConfigInfo->dwParams & RIL_PARAM_CBMC_BROADCASTMSGLANGS)
        {
            MakeBroadcastLangRange(lpMsgConfigInfo->dwBroadcastMsgLangs, szCBMsgLangs, MAX_PATH);

            (void)_snprintfz(szWalk, MAX_PATH - (szWalk - szCmd), "%s,\"%s\"", (lpMsgConfigInfo->dwParams & RIL_PARAM_CBMC_BROADCASTMSGIDS)?"":",", szCBMsgLangs);
            szWalk = strchr(szWalk, '\0');  // NO_TYPO: 27
            DEBUGCHK(NULL != szWalk);
        }
#endif
    }

    (void)_snprintfz(szWalk, MAX_PATH - (szWalk - szCmd), ";+CSAS\r");

    if (!QueueCmd(pHandle, szCmd, CMDOPT_NONE, APIID_SETCBMSGCONFIG, NULL, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }

    Error:
    return hr;
}

//
//
//
static HRESULT ParseReadMsg(LPCSTR szRsp, void*& pBlob, UINT& cbBlob)
{
    FUNCTION_TRACE(ParseReadMsg);
    UINT nValue;
    UINT cbMessage;
    BOOL fIncoming;
    RILMESSAGEINFO* prmi = NULL;
    HRESULT hr = S_OK;

    pBlob = NULL;
    cbBlob = 0;

    prmi = (RILMESSAGEINFO*)AllocBlob(sizeof(RILMESSAGEINFO));
    if (!prmi)
    {
        hr = E_OUTOFMEMORY;
        goto Error;
    }
    memset(prmi, 0x00, sizeof(RILMESSAGEINFO));
    prmi->cbSize = sizeof(RILMESSAGEINFO);

    // Parse "<prefix>+CMGR: <stat>"
    if (!ParseRspPrefix(szRsp, szRsp)                  ||
        !MatchStringBeginning(szRsp, "+CMGR: ", szRsp) ||
        !ParseUInt(szRsp, TRUE, nValue, szRsp))
    {
#if defined(OEM2_DRIVER)
		hr = RIL_E_INVALIDINDEX;		// OEM1 and Wavecom return +CMS ERROR 321 whereas OEM1 returns OK. Mangle OEM2 response.
#else
		hr = E_FAIL;
#endif
        goto Error;
    }

    if (NUM_MSGSTATS > nValue)
    {
        prmi->dwStatus = g_rgdwMsgStats[nValue];
    }
    else
    {
        prmi->dwStatus = RIL_MSGSTATUS_UNKNOWN;
    }
    prmi->dwParams |= RIL_PARAM_MI_STATUS;

    // Parse",<alpha>" (if present)
    if (!MatchStringBeginning(szRsp, ",", szRsp))
    {
        hr = E_FAIL;
        goto Error;
    }

    // Copy alpha to temp buffer & throw away
    TCHAR szBuf[MAXLENGTH_ADDRESS];
    (void)ParseQuotedEncodedString(ENCODING_TECHARSET, szRsp, szBuf, szBuf + MAXLENGTH_ADDRESS);

    // Parse ",<length><postfix>"
    if (!MatchStringBeginning(szRsp, ",", szRsp)  ||
        !ParseUInt(szRsp, TRUE, nValue, szRsp) ||
        !ParseRspPostfix(szRsp, szRsp))
    {
        hr = E_FAIL;
        goto Error;
    }

    // Calculate the total number of bytes in the message data: (length of the PDU data +
    //    length os SC address (stored in the first 2 bytes) + 1) * 2
    cbMessage = (nValue + 1 + SemiByteCharsToByte(*szRsp, *(szRsp + 1))) * 2;

    // Parse "<pdu>"
    fIncoming = (RIL_MSGSTATUS_RECUNREAD == prmi->dwStatus ||
                 RIL_MSGSTATUS_RECREAD == prmi->dwStatus);
    hr = ParseSMSMessage(szRsp, cbMessage, fIncoming, TRUE, prmi->rmMessage);
    if (FAILED(hr))
    {
        goto Error;
    }
    szRsp += cbMessage;
    prmi->dwParams |= RIL_PARAM_MI_MESSAGE;

    // Parse "<postfix>"
    if (!ParseRspPostfix(szRsp, szRsp))
    {
        hr = E_FAIL;
        goto Error;
    }

    // NOTE: there may be more data in the response (if we also deleted the message),
    //       but we don't care about it

    pBlob = (void*)prmi;
    cbBlob = sizeof(RILMESSAGEINFO);

    Error:
    if (FAILED(hr))
    {
        FreeBlob(prmi);
    }
    return hr;
}


//
//
//
HRESULT RILDrv_ReadMsg(DWORD dwParam, DWORD dwIndex)
{
    FUNCTION_TRACE(RILDrv_ReadMsg);
    CNotificationData* pnd = NULL;
    char szCmd[MAX_PATH];
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle)
    {
        hr = E_FAIL;
        goto Error;
    }

    (void)_snprintfz(szCmd, MAX_PATH, "AT+CMGR=%u\r", dwIndex);
    if (!QueueCmd(pHandle, szCmd, CMDOPT_NONE, APIID_READMSG, ParseReadMsg, pnd, hr))
    {
        hr = E_FAIL;
        goto Error;
    }
    pnd = NULL;

    Error:
    return hr;
}


//
//
//
HRESULT RILDrv_DeleteMsg(DWORD dwParam, DWORD dwIndex)
{
    FUNCTION_TRACE(RILDrv_DeleteMsg);
    CNotificationData* pnd = NULL;
    char szCmd[MAX_PATH];
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle)
    {
        hr = E_FAIL;
        goto Error;
    }

    pnd = new CNotificationData;
    if (pnd && !pnd->InitFromDWORDBlob(RIL_NOTIFY_MSGDELETED, dwIndex))
    {
        delete pnd;
        pnd = NULL;
    }
    (void)_snprintfz(szCmd, MAX_PATH, "AT+CMGD=%u\r", dwIndex);
    if (!QueueCmd(pHandle, szCmd, CMDOPT_NONE, APIID_DELETEMSG, NULL, pnd, hr))
    {
        hr = E_FAIL;
        goto Error;
    }
    pnd = NULL;

    Error:
    return hr;
}


//
//
//
static HRESULT ParseWriteMsg(LPCSTR szRsp, void*& pBlob, UINT& cbBlob)
{
    FUNCTION_TRACE(ParseWriteMsg);
    UINT nValue;
    DWORD* pdwIndex = NULL;
    HRESULT hr = E_FAIL;

    pBlob = NULL;
    cbBlob = 0;

    pdwIndex = (DWORD*)AllocBlob(sizeof(DWORD));
    if (!pdwIndex)
    {
        hr = E_OUTOFMEMORY;
        goto Error;
    }
    memset(pdwIndex, 0x00, sizeof(DWORD));

    // Parse "+CMGW: <index><postfix>"
    if (!MatchStringAnywhere(szRsp, "+CMGW: ", szRsp) ||
        !ParseUInt(szRsp, TRUE, nValue, szRsp)        ||
        !ParseRspPostfix(szRsp, szRsp))
    {
        goto Error;
    }

    *pdwIndex = (DWORD)nValue;

    pBlob = (void*)pdwIndex;
    cbBlob = sizeof(DWORD);
    hr = S_OK;

    Error:
    if (FAILED(hr))
    {
        FreeBlob(pdwIndex);
    }
    return hr;
}


//
//
//
HRESULT RILDrv_WriteMsg(DWORD dwParam, const RILMESSAGE *lpMessage, DWORD dwStatus)
{
    FUNCTION_TRACE(RILDrv_WriteMsg);
    CNotificationData* pnd = NULL;
    char szCmd[MSG_CMDBUF_LENGTH];
    char szCmd2[MSG_CMDBUF_LENGTH];
    char szMessage[MSG_MSGBUF_LENGTH];
    UINT cbMessage;
    UINT nGSMLength;
    UINT nValue;
    UINT i;
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle || !lpMessage)
    {
        hr = E_FAIL;
        goto Error;
    }

    hr = EncodeSMSMessage(*lpMessage, szMessage, MSG_MSGBUF_LENGTH - 1, cbMessage, nGSMLength);
    if (FAILED(hr))
    {
        goto Error;
    }
    if (!cbMessage)
    {
        hr = E_FAIL;
        goto Error;
    }
    szMessage[cbMessage] = '\0';

    for (i = 0; i < NUM_MSGSTATS; i++)
    {
        if (dwStatus == g_rgdwMsgStats[i])
        {
            nValue = i;
            break;
        }
    }
    if (NUM_MSGSTATS == i)
    {
        hr = E_INVALIDARG;
        goto Error;
    }

    pnd = new CNotificationData;
    if (pnd && !pnd->DelayInitFromRspBlob(RIL_NOTIFY_MSGSTORED))
    {
        delete pnd;
        pnd = NULL;
    }
    (void)_snprintfz(szCmd, MSG_CMDBUF_LENGTH, "AT+CMGW=%u,%u\r", nGSMLength, nValue);
    (void)_snprintfz(szCmd2, MSG_CMDBUF_LENGTH,  "%s\x1a", szMessage);
    if (!QueueMultipartCmd(pHandle, szCmd, szCmd2, CMDOPT_INTERMEDIATERESPONSE, APIID_WRITEMSG, ParseWriteMsg, pnd, hr))
    {
        hr = E_FAIL;
        goto Error;
    }
    pnd = NULL;

    Error:
    return hr;
}


//
//
//
static HRESULT ParseSendMsg(LPCSTR szRsp, void*& pBlob, UINT& cbBlob)
{
    FUNCTION_TRACE(ParseSendMsg);
    UINT nValue;
    DWORD* pdwMsgRef = NULL;
    HRESULT hr = E_FAIL;

    pBlob = NULL;
    cbBlob = 0;

    pdwMsgRef = (DWORD*)AllocBlob(sizeof(DWORD));
    if (!pdwMsgRef)
    {
        hr = E_OUTOFMEMORY;
        goto Error;
    }
    memset(pdwMsgRef, 0x00, sizeof(DWORD));

    if (!MatchStringAnywhere(szRsp, "+CMGS: ", szRsp) &&
        !MatchStringAnywhere(szRsp, "+CMGC: ", szRsp))
    {
        goto Error;
    }

    // Parse "<msgref><CR><LF>"
    if (!ParseUInt(szRsp, TRUE, nValue, szRsp) ||
        !ParseRspPostfix(szRsp, szRsp))
    {
        goto Error;
    }

    *pdwMsgRef = (DWORD)nValue;

    pBlob = (void*)pdwMsgRef;
    cbBlob = sizeof(DWORD);
    hr = S_OK;

    Error:
    if (FAILED(hr))
    {
        FreeBlob(pdwMsgRef);
    }
    return hr;
}


//
//
//
HRESULT RILDrv_SendMsg(DWORD dwParam, const RILMESSAGE *lpMessage, DWORD dwOptions)
{
    FUNCTION_TRACE(RILDrv_SendMsg);
    char szCmd[MSG_CMDBUF_LENGTH];
    char szCmd2[MSG_CMDBUF_LENGTH];
    LPCSTR szATCmd;
    char szMessage[MSG_MSGBUF_LENGTH];
    UINT cbMessage;
    UINT nGSMLength;
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle || !lpMessage)
    {
        hr = E_FAIL;
        goto Error;
    }

    // We can only send outgoing messages
    if (RIL_MSGCLASS_OUTGOING != MSGCLASS_FROM_MSGTYPE(lpMessage->dwType))
    {
        hr = E_INVALIDARG;
        goto Error;
    }

    hr = EncodeSMSMessage(*lpMessage, szMessage, MSG_MSGBUF_LENGTH - 1, cbMessage, nGSMLength);
    if (FAILED(hr))
    {
        goto Error;
    }
    if (!cbMessage)
    {
        hr = E_FAIL;
        goto Error;
    }
    szMessage[cbMessage] = '\0';

    if ((RIL_MSGTYPE_OUT_SUBMIT == lpMessage->dwType) || (RIL_MSGTYPE_OUT_RAW == lpMessage->dwType))
    {
        szATCmd = "CMGS";
    }
    else if (RIL_MSGTYPE_OUT_COMMAND == lpMessage->dwType)
    {
        szATCmd = "CMGC";
    }
    else
    {
        hr = E_INVALIDARG;
        goto Error;
    }

    if (dwOptions & RIL_SENDOPT_PERSISTLINK)
    {
        (void)_snprintfz(szCmd, MSG_CMDBUF_LENGTH, "AT+CMMS=1;+%s=%u\r", szATCmd, nGSMLength);
    }
    else
    {
        (void)_snprintfz(szCmd, MSG_CMDBUF_LENGTH, "AT+%s=%u\r", szATCmd, nGSMLength);
    }

    (void)_snprintfz(szCmd2, MSG_CMDBUF_LENGTH,  "%s\x1a", szMessage);

    if (!QueueMultipartCmd(pHandle, szCmd, szCmd2, CMDOPT_RETRYONSIMLOCKED | CMDOPT_INTERMEDIATERESPONSE, APIID_SENDMSG, ParseSendMsg, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }

    Error:
    return hr;
}


//
//
//
static HRESULT ParseSendStoredMsg(LPCSTR szRsp, void*& pBlob, UINT& cbBlob)
{
    FUNCTION_TRACE(ParseSendStoredMsg);
    UINT nValue;
    DWORD* pdwMsgRef = NULL;
    HRESULT hr = S_OK;

    pBlob = NULL;
    cbBlob = 0;

    pdwMsgRef = (DWORD*)AllocBlob(sizeof(DWORD));
    if (!pdwMsgRef)
    {
        hr = E_OUTOFMEMORY;
        goto Error;
    }
    memset(pdwMsgRef, 0x00, sizeof(DWORD));

    // Parse "<prefix>+CMSS: <msgref><postfix>"
    if (!ParseRspPrefix(szRsp, szRsp)                  ||
        !MatchStringBeginning(szRsp, "+CMSS: ", szRsp) ||
        !ParseUInt(szRsp, TRUE, nValue, szRsp)         ||
        !ParseRspPostfix(szRsp, szRsp))
    {
        hr = E_FAIL;
        goto Error;
    }

    *pdwMsgRef = (DWORD)nValue;

    pBlob = (void*)pdwMsgRef;
    cbBlob = sizeof(DWORD);

    Error:
    if (FAILED(hr))
    {
        FreeBlob(pdwMsgRef);
    }
    return hr;
}


//
//
//
HRESULT RILDrv_SendStoredMsg(DWORD dwParam, DWORD dwIndex, DWORD dwOptions)
{
    FUNCTION_TRACE(RILDrv_SendStoredMsg);
    char szCmd[MAX_PATH];
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle)
    {
        hr = E_FAIL;
        goto Error;
    }

    if (dwOptions & RIL_SENDOPT_PERSISTLINK)
    {
        (void)_snprintfz(szCmd, MAX_PATH, "AT+CMMS=1;+CMSS=%u\r", dwIndex);
    }
    else
    {
        (void)_snprintfz(szCmd, MAX_PATH, "AT+CMSS=%u\r", dwIndex);
    }

    if (!QueueCmd(pHandle, szCmd, CMDOPT_RETRYONSIMLOCKED, APIID_SENDSTOREDMSG, ParseSendStoredMsg, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }

    Error:
    return hr;
}


//
//
//
HRESULT RILDrv_SendMsgAcknowledgement(DWORD dwParam, BOOL fSuccess)
{
    FUNCTION_TRACE(RILDrv_SendMsgAcknowledgement);
    char szCmd[MAX_PATH];
    HRESULT hr = S_OK;
    CRilInstanceHandle* pHandle = ExtractHandle(dwParam);
    if (!pHandle)
    {
        hr = E_FAIL;
        goto Error;
    }

    (void)_snprintfz(szCmd, MAX_PATH, "AT+CNMA=%u\r", fSuccess ? 1 : 2);
    if (!QueueCmd(pHandle, szCmd, CMDOPT_NONE, APIID_SENDMSGACKNOWLEDGEMENT, NULL, NULL, hr))
    {
        hr = E_FAIL;
        goto Error;
    }

    Error:
    return hr;
}
